using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using SimpleSocket.Args;
using SimpleSocket.Packets;
using SimpleSocket.Protocols;

namespace SimpleSocket
{
    public abstract class Host
    {
        private readonly IProtocol _protocol;
        
        /// <summary>
        /// 发送超时
        /// </summary>
        public int SendDataTimeout { get; set; } = 3000;

        /// <summary>
        /// 消息接收超时
        /// </summary>
        public int ReceiveDataTimeout { get; set; } = 3000;
        
        /// <summary>
        /// 单条消息收发长度限制
        /// </summary>
        public int SocketBufferSize { get; set; } = 8192;
        
        protected Host(IProtocol protocol)
        {
            _protocol = protocol;
        }
        
        protected virtual void OnConnectionChanged(string remote, bool success)
        {
            
        }

        protected virtual void OnSendDataCallback(string remote, byte[] data, bool success)
        {
            
        }

        protected virtual void OnReceiveMessage(string remote, byte[] data)
        {
            
        }
        
        
        internal virtual void OnDisconnect(string remote,Exception error)
        {
            
        }
        
        internal void OnSendCallback(string remote, Packet packet, bool success)
        {
            OnSendDataCallback(remote,packet.Payload, success);
        }

        internal void OnReceived(string remote,MessageReceivedEventArgs e)
        {
            byte[] realData;
            int readLen;
            if (_protocol != null)
            {
                realData = _protocol.Parse(e.Buffer, out readLen);
            }
            else
            {
                realData = new byte[e.Buffer.Count];
                Buffer.BlockCopy(e.Buffer.Array, 0, realData, 0, e.Buffer.Count);
                readLen = realData.Length;
            }

            e.SetReadLength(readLen);
            if (realData == null)
                return;
            OnReceiveMessage(remote,realData);
        }
    }
}